<?php
/**
 * Created by PhpStorm.
 * User: xushuhui
 * Date: 2017/12/5
 * Time: 11:54
 */

namespace App\Http\Controllers;


use App\Post;
use App\Comment;
use App\Zan;
use Illuminate\Http\Request;

class PostController extends Controller
{
    //文章列表页
    public function index()
    {
        //$posts = Post::orderBy('created_at','desc')->withCount(["comments",'zans'])->paginate(2);
        $user = \Auth::user();
        $posts = Post::orderBy('created_at', 'desc')->withCount(["zans", "comments"])->with(['user'])->paginate(6);
        return view('post/index',compact('posts'));
    }
    //文章详情页面
    public function show(Post $post)
    {
        $post->load('comments');//预加载
        $user = \Auth::user();
        return view('post/show',compact('post','user'));
    }
    //创建文章页面
    public function create()
    {
        $user = \Auth::user();
        return view('post/create',compact('user'));
    }
    //创建文章逻辑
    public function store(Request $request)
    {
        $this->validate($request,[
            'title' => 'required|string|max:100|min:5',
            'content' => 'required|string|min:10'
        ]);
        $user_id = \Auth::id();
        $params = array_merge(request(['title','content']),compact('user_id'));
        $post = Post::create($params);
        return redirect("/posts");
    }

    //编辑文章页面
    public function edit(Post $post)
    {
        return view('post/edit',compact('post'));
    }
    //编辑文章逻辑
    public function update(Post $post)
    {
        // TODO 用户权限验证
        $this->validate(request(),[
            'title' => 'required|string|max:100|min:5',
            'content' => 'required|string|min:10'
        ]);
        //权限控制
        $this->authorize('update',$post);
        //添加到数据库
        $post->title = request('title');
        $post->content = request('content');
        $post->save();
        return redirect("/posts/{$post->id}");
    }
    // 删除文章
    public function delete(Post $post)
    {
        $this->authorize('delete',$post);
        $post->delete();
        return redirect("/posts");
    }
    // 上传图片
    public function imageUpload(Request $request)
    {
        $path = $request->file('wangEditorH5File')->storePublicly(md5(time()));
        return asset('storage/'. $path);
    }
    //提交评论
    public function comment(Post $post)
    {
        $this->validate(request(),[
            'content' => 'required|string|min:3'
        ]);
        $comment = new Comment();
        $comment->user_id = \Auth::id();
        $comment->content = request('content');
        $post->comments()->save($comment);
        return back();
    }
    //赞
    public function zan()
    {
        $params = [
            'user_id' => \Auth::id(),
            'post_id' =>$post->id
        ];
        Zan::firstOrCreate($params);
        return back();
    }
    //取消赞
    public function unzan()
    {
        $post->zan(\Auth::id())->delete();
        return back();
    }
}